# 梦幻提示音生成
# 生成一个总时长为 total_time 分钟的梦幻提示音，中间每隔 random_start 分钟到 random_end 分钟插入一个随机提示音，固定提示音时长为输入提示音的时长。
# ps: 要执行本地需要安装 ffmpeg 并添加到环境变量中
from random import random, randint
from pydub import AudioSegment


# empty_voice_path: 空音路径
# remind_voice_path: 提示音路径
# ends_voice_path: 结束音路径
# output_path: 输出路径
# random_start: 随机插入提示音的最小时间间隔（分钟）
# random_end: 随机插入提示音的最大时间间隔（分钟）
# total_time: 总时长（分钟）
def generate_menghuan(empty_voice_path, remind_voice_path, ends_voice_path, output_path,
                      random_start, random_end, total_time):
    empty_voice = AudioSegment.from_mp3(empty_voice_path)
    remind_voice = AudioSegment.from_mp3(remind_voice_path)
    ends_voice = AudioSegment.from_mp3(ends_voice_path)
    empty_len = len(empty_voice) / 1000
    remind_len = len(remind_voice) / 1000
    output_voice = AudioSegment.empty()
    start_s = random_start * 60
    end_s = random_end * 60
    total_time_s = total_time * 60

    remind_time = 0
    while True:
        cur_total_len = len(output_voice) / 1000
        print(f"当前总时长: {cur_total_len / 60} 分, 提示次数: {remind_time}")
        random_num = int(randint(start_s, end_s) / empty_len)
        if cur_total_len + (random_num * empty_len + remind_len) > total_time_s:
            last_num = int((total_time_s - cur_total_len) / empty_len)
            for i in range(last_num):
                output_voice = output_voice + empty_voice
            output_voice = output_voice + ends_voice
            break
        for i in range(random_num):
            output_voice = output_voice + empty_voice
        output_voice = output_voice + remind_voice
        remind_time += 1

    output_voice.export(output_path, format="mp3")
    print(f"生成完成，总时长: {len(output_voice) / 1000 / 60} 分, 提示次数: {remind_time}")

def do_multi_times_generate(empty_voice_path, remind_voice_path, ends_voice_path, output_path,
                      random_start, random_end, total_time, gen_nums = 1):
    for i in range(0, gen_nums):
        generate_menghuan(empty_voice_path, remind_voice_path,
            ends_voice_path, output_path, random_start, random_end, total_time)


if __name__ == '__main__':
    base_path = "C:/workspaceFinal/AdobeAu/拼接原始音/"
    save_path = "C:/workspaceFinal/AdobeAu/拼接原始音/梦幻提示/"
    do_multi_times_generate(base_path + "无声real_10s_192kbps.mp3", base_path + "梦幻提示音_11s_192kbps.mp3",
        base_path + "思念_192kpbs.mp3", save_path + f"梦幻提示_{i}.mp3",
        3, 5, 90, 10)



